//
//  PictureCell.swift
//  新浪微博01
//
//  Created by 李国伟 on 15/12/18.
//  Copyright © 2015年 李国伟. All rights reserved.
//

import UIKit
import SDWebImage
///  设定协议
protocol PictureCellDelgate: NSObjectProtocol {
    func pictureCellclickImage()
    func pictureCellDidZoom(scacle: CGFloat)
}
class PictureCell: UICollectionViewCell {
    
    //添加代理属性
    weak var delegate: PictureCellDelgate?
    
    var imageUrl : NSURL? {
        didSet{
            
            //重设scroView
            resetContentView()
            
            //设置占位图片
            setPlaceHoderImage()
            
            //下载高清大图
           imageView.sd_setImageWithURL(bigmidUrl(imageUrl!),placeholderImage: nil,
               options: [SDWebImageOptions.RetryFailed,SDWebImageOptions.RefreshCached],
               progress: { (all, current) -> Void in
                
               //计算下载进度并返回主线程更新UI
               let progress = CGFloat(all) / CGFloat(current)
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.placeHoderView.progress = progress
                })
                
            }) { (image, _, _, _) -> Void in
                self.placeHoderView.hidden = true
                self.setPostion(self.imageView)
            }
        }
    }
    
    //添加代理方法
    @objc private func clickImageView(){
        delegate?.pictureCellclickImage()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
     lazy var scrollView: UIScrollView = UIScrollView()
        lazy var imageView: UIImageView = {
        let imageview = UIImageView()
        let tap = UITapGestureRecognizer(target: self, action: "clickImageView")
        imageview.userInteractionEnabled = true
        imageview.addGestureRecognizer(tap)
        return imageview
    }()
    private lazy var placeHoderView: PictureLoadingView = PictureLoadingView()
    //MARK: 设置控件
    private func setupUI(){
        
        contentView.addSubview(scrollView)
        scrollView.addSubview(placeHoderView)
        scrollView.addSubview(imageView)
        
        //问题,已解决
        var rect = bounds
        rect.size.width -= 20
        scrollView.frame = rect
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2
        scrollView.delegate = self
    }
    
    //设置占位图片
    private func setPlaceHoderImage() {
        placeHoderView.hidden = false
        let palceHoder = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(imageUrl?.absoluteString)
        placeHoderView.image = palceHoder
        placeHoderView.sizeToFit()
        placeHoderView.center = contentView.center
    }
    
    //防止cell重用清空scroview的约束
    private func resetContentView(){
        scrollView.contentSize = CGSizeZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.transform = CGAffineTransformIdentity
    }
    
    //设置图片frame
    private func setPostion(imageView: UIImageView){
        
        guard let image = imageView.image else{
            return
        }
        
        let size = displaySize(image)
        
        //判断是否为大图，如果为大图，设置滚动范围
        if size.height < scrollView.bounds.height {
            imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            let y = (scrollView.bounds.height - size.height) * 0.5
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
        }else{
            scrollView.contentSize = size
            imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        }
        
    }
    
    //计算图片原比例大小
    private func displaySize(image: UIImage) -> CGSize{
        
        let w = scrollView.bounds.size.width
        let h = image.size.height * w / image.size.width
        
        return CGSize(width: w, height: h)
    }
    
    //转换大图的URL 
    private func bigmidUrl(imageUrl: NSURL) -> NSURL{
        
        var str = imageUrl.absoluteString
        str = str.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        return NSURL(string: str)!
    }
}

//MARK： 设置scrollView的代理方法
extension PictureCell: UIScrollViewDelegate {
    
    //返回要放缩的图片
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    //执行完放缩,更改控件的frame
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        //如果比图片下自动关闭控制器
        if scale < 1 {
            delegate?.pictureCellclickImage()
            return
        }
        
        var offsetY = (scrollView.frame.height - imageView.frame.height) * 0.5
        offsetY = offsetY > 0 ? offsetY : 0
        
        var offsetX = (scrollView.frame.width - imageView.frame.width) * 0.5
        offsetX = offsetX > 0 ? offsetX : 0
        
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
    }
    
    //放缩完成后要关闭控制器,实现交互式过场动画
    func scrollViewDidZoom(scrollView: UIScrollView) {
        
        delegate?.pictureCellDidZoom(imageView.transform.a)
    }
}
